{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline\n",
    "#%matplotlib notebook"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Ejemplo 1: Frecuencia de letras en El Quijote\n",
    "Tenemos un fichero `'quijote.txt'`, con El Quijote en texto plano. Queremos hacer un histograma de frecuencias de cada letra, es decir, saber qué porcentaje de veces aparece la `'a'`, la `'b'`, etc.\n",
    "\n",
    "La herramienta perfecta para llevar el recuento es un diccionario, que asocia a cada letra el número de apariciones."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'t': 0.03920350287259837, 'h': 0.012660619569351847, 'e': 0.1386628076257358, 'p': 0.022248543876973247, 'r': 0.06326716713603739, 'o': 0.0958426928704797, 'j': 0.006583373497259974, 'c': 0.03719943650733668, 'g': 0.010927892019541351, 'u': 0.048765408389697056, 'n': 0.06783036739771207, 'b': 0.01513240466901001, 'k': 8.239283665527209e-05, 'f': 0.004935516764154532, 'd': 0.05437927219247958, 'q': 0.020134207399496225, 'i': 0.04878089576500819, 'y': 0.015761811601654796, 'm': 0.02789214344035316, 'l': 0.05552657695552893, 'v': 0.01113604234372309, 'a': 0.12041124556906192, 's': 0.07836116311427577, 'x': 0.0002521344700653815, 'z': 0.004022381115809636}\n"
     ]
    }
   ],
   "source": [
    "#urlWords = r'https://www.gutenberg.org/files/2000/2000-8.txt'\n",
    "urlWords = r'C:/Users/mfc06/Desktop/quijote.txt'\n",
    "letras = set('abcdefghijklmnopqrstuvxyz')\n",
    "conteo = {}\n",
    "\n",
    "with open(urlWords) as f:\n",
    "    for line in f:\n",
    "        for letra in line:\n",
    "            letra = letra.lower()\n",
    "            if letra in letras:\n",
    "                if letra in conteo:\n",
    "                    conteo[letra] += 1\n",
    "                else:\n",
    "                    conteo[letra] = 1\n",
    "                    \n",
    "# Construimos las probabilidades\n",
    "nbLetras = sum(conteo.values())\n",
    "prob = {}\n",
    "for (letra, freq) in conteo.items():\n",
    "    prob[letra] = freq / nbLetras\n",
    "print(prob)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Hacemos un gráfico de barras."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.ticker import FuncFormatter\n",
    "\n",
    "def to_percent(y, position):\n",
    "    \"\"\"Produce numeros en porcentaje, sin trailing 0s\"\"\"\n",
    "    return str(100 * y).rstrip('0').rstrip('.') + '%'\n",
    "\n",
    "\n",
    "plt.figure(1, figsize = (10,5))  # Dimensiones zona plot\n",
    "axes = plt.gca()\n",
    "\n",
    "# Example data\n",
    "claves = sorted(prob)\n",
    "fs = []\n",
    "for clave in claves:\n",
    "    fs.append(prob[clave])\n",
    "\n",
    "ancho = 0.3\n",
    "nDatos = len(claves)\n",
    "x_pos = np.linspace(0, ancho*(nDatos-1), nDatos)  # Alturas a las que va cada barra\n",
    "\n",
    "# Rangos abarcados en los ejes\n",
    "axes.set_xlim([-0.5*ancho, ancho*(nDatos-0.5)])\n",
    "axes.set_ylim([0, max(fs) + 0.01])\n",
    "\n",
    "# Porcentajes en el eje X\n",
    "axes.yaxis.set_major_formatter(FuncFormatter(to_percent))\n",
    "\n",
    "plt.bar(x_pos, height=fs, width=0.82*ancho, xerr=None, align='center', alpha=0.4)\n",
    "plt.xticks(x_pos, claves)  # Cambio en los yticks: ponemos las letras\n",
    "plt.xlabel('Letra')\n",
    "plt.ylabel('Frecuencia')\n",
    "plt.title('Letras en El Quijote');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> El conteo de frecuencias en una lista (o iterable) es tan habitual que existe una clase justamente para eso: `collections.Counter`."
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
